package code.wrtp.packets;

import code.exceptions.BadPduFormatException;
import code.wrtp.FrameControlType;

/*Represents Data from user*/
public class DataPacket implements Packet {

	private byte FC;
	private short SA;
	private short DA;
	private short RA;
	private byte[] data;

	public DataPacket() {
	}

	public DataPacket(byte FC, short SA, short DA, short RA, byte[] data) {
		this.FC = FC;
		this.SA = SA;
		this.DA = DA;
		this.RA = RA;
		this.data = data;
	}

	public short getSourceNodeAddress() {
		return SA;
	}

	public short getDestinationNodeAddress() {
		return DA;
	}

	public short getRingAddress() {
		return RA;
	}

	public byte[] getData() {
		return data;
	}

	@Override
	public byte[] toBytes() {
		return toString().getBytes();
	}

	public String toString() {
		return FC + ";" + RA + ";" + DA + ";" + SA + ";" + new String(data);
	}

	@Override
	public void ParseBytes(byte[] pduRaw) throws BadPduFormatException {
		String []splittedPacket = new String(pduRaw).split(";", 5);
		if (splittedPacket.length != 5) {
			throw new BadPduFormatException("Wrong packet format!");
		}
		
		FC = Byte.parseByte(splittedPacket[0]);
		if ((FC != FrameControlType.DATA_PACKET) && (FC != FrameControlType.VARAL_DATA_PACKET)) {
			throw new BadPduFormatException("Wrong packet format!");
		}
		RA = Short.parseShort(splittedPacket[1]);
		DA = Short.parseShort(splittedPacket[2]);
		SA = Short.parseShort(splittedPacket[3]);
		data = splittedPacket[4].getBytes();
	}

}
